import logging

from flask import abort
from flask import g
from flask import redirect
from flask import render_template, current_app, jsonify
from flask import request
from flask import session

from info import constants, db
from info.models import User, Category, News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import user_blue


@user_blue.route('/other_news_list')
@user_login_data
def other_news_list():
    user = g.user
    # 分页显示
    page = request.args.get('p')
    user_id = request.args.get('user_id')

    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if not all([page, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 查询此用户
    try:
        user = User.query.get(user_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
        # 从数据库取值，要判断它是否为空
    if not user:
        return jsonify(errno=RET.NODATA, errmsg='无该用户信息')

    # 查询该用户发布的新闻
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_review_dict())

    data = {
        'user': user.to_dict(),
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg='成功', data=data)


@user_blue.route('/other_info')
@user_login_data
def other_info():
    user = g.user
    # 获取其他用户的id
    other_id = request.args.get('user_id')
    # 查询
    other_user = None
    try:
        other_user = User.query.get(other_id)
    except Exception as e:
        logging.error(e)
        abort(500)
    if not other_user:
        abort(404)
    # 判断当前用户是否关注过该作者
    is_followed = False
    if user in other_user.followers:
        is_followed = True

    data = {
        "user": user.to_dict(),
        "other_info": other_user.to_dict(),
        "is_followed": is_followed
    }
    return render_template('news/other.html', data=data)


@user_blue.route('/user_follow')
@user_login_data
def user_follow():
    user = g.user
    # 分页显示
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 查询数据库
    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        follows = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    user_dict_li = []
    for follow in follows:
        user_dict_li.append(follow.to_dict())

    data = {
        'users': user_dict_li,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('news/user_follow.html', data=data)


@user_blue.route('/news_list')
@user_login_data
def news_list():
    user = g.user
    # 获取数据
    page = request.args.get('page', 1)
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1
    # 分页查询
    news_models = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_models = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        logging.error(e)

    news_list = []
    for news in news_models:
        news_list.append(news)

    data = {
        'news_list': news_list,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('news/user_news_list.html', data=data)


# 新闻发布
@user_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    if request.method == 'GET':

        # 获取参数
        category_models = []
        try:
            category_models = Category.query.all()
        except Exception as e:
            logging.error(e)

        # 数据转字典
        category_list = []
        for category in category_models:
            category_list.append(category)
        category_list.pop(0)

        data = {
            'category_list': category_list
        }

        return render_template('news/user_news_release.html', data=data)

    # POST请求下的逻辑处理
    # 1. 获取参数
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    source = "个人发布"

    # 校验参数
    # 完整性
    if not all([title, category_id, digest, index_image, content, source]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 图片的读取
    try:
        index_image = index_image.read()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 分类ID的校验
    try:
        category_id = int(category_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        category = Category.query.get(category_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询出错')
        # 从数据库取值，要判断它是否为空
    if not category:
        return jsonify(errno=RET.NODATA, errmsg='没有该分类')

    # 逻辑处理
    # 将图片上传至七牛云
    try:
        image_name = storage(index_image)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='第三方上传错误')

    # 创建模型，并提交
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1
    # 提交数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库上传错误')
    return jsonify(errno=RET.OK, errmsg='发布成功，审核中')


@user_blue.route('/collection')
@user_login_data
def collection():
    # 获取参数
    user = g.user
    page = request.args.get('page', 1)
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1
    # 分页查询
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collection_models = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        logging.error(e)
        collection_models = []
        current_page = 1
        total_page = 1
        return jsonify(errno=RET.DBERR, errmsg='数据查询出错')
    collection_list = []
    for news in collection_models:
        collection_list.append(news)

    data = {
        'collection_list': collection_list,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('news/user_collection.html', data=data)


@user_blue.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    # 获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    # 校验参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg='原始密码错误')
    # 对新密码进行更新
    user.password = new_password
    # 提交
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='提交数据出错')
    # 返回数据
    return jsonify(errno=RET.OK, errmsg='成功')


@user_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})
    try:
        avatar_file = request.files.get('avatar').read()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='读取文件错误')
    # 文件上传至七牛云
    try:
        avatar_name = storage(avatar_file)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传第三方错误')
    # 将图片设置到用户数据中
    user.avatar_url = avatar_name
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='上传错误')
    return jsonify(errno=RET.OK, errmsg='成功', data={"avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_name})


@user_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    user = g.user
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    # 获取数据
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    # 校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 逻辑处理
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库提交错误')
    # 保存session
    session['nick_name'] = nick_name
    # 返回数据
    return jsonify(errno=RET.OK, errmsg='成功')


@user_blue.route('/info')
@user_login_data
def info():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user': user.to_dict()
    }
    return render_template('news/user.html', data=data)
